package net.mfjassociates.financial.server.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import net.mfjassociates.financial.shared.domain.Document;

public class DocumentResource {
	@Context
	UriInfo uriInfo;
	@Context
	Request request;
	String iden;
	public DocumentResource(UriInfo uriInfo, Request request, String iden) {
		this.uriInfo = uriInfo;
		this.request = request;
		this.iden = iden;
	}
	
	//Application integration 		
	@GET
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public Document getDocument() {
		Document document = Document.findDocumentByIden(iden);
		if(document==null)
			throw new RuntimeException("Get: document with " + iden +  " not found");
		return document;
	}
	
	// For the browser
	@GET
	@Produces(MediaType.TEXT_XML)
	public Document getDocumentHTML() {
		Document document = Document.findDocumentByIden(iden);
		if(document==null)
			throw new RuntimeException("Get: document with " + iden +  " not found");
		return document;
	}
	
	@PUT
	@Consumes(MediaType.APPLICATION_XML)
	public Response putDocument(JAXBElement<Document> document) {
		Document c = document.getValue();
		return putAndGetResponse(c);
	}
	
	@DELETE
	public void deleteDocument() {
		Document c = Document.findDocumentByIden(iden);
		if(c==null) {
			throw new RuntimeException("Delete: document with " + iden +  " not found");
		} else {
			c.remove();
		}
	}
	
	private Response putAndGetResponse(Document document) {
		Response res;
		if(Document.findDocumentByIden(document.getIden())!=null) {
			res = Response.noContent().build();
			document.merge();
		} else {
			res = Response.created(uriInfo.getAbsolutePath()).build();
			document.persist();
		}
		return res;
	}
	
	

}
